﻿using System;
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;

namespace AspnetUtil.Web.Config.DI
{
    /// <summary>
    /// 拓展 service
    /// </summary>
    public static class ServiceCollectionExtend
    {
        /// <summary>
        /// 自动注册 bean
        /// </summary>
        /// <param name="serviceCollection"></param>
        /// <returns></returns>
        public static IServiceCollection AutoRegisterServiceCollection(this IServiceCollection serviceCollection)
        {
            foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                foreach (Type type in assembly.GetTypes())
                {
                    // 注册 service
                    RegisterService(serviceCollection, type);
                }
            }

            return serviceCollection;
        }

        /// <summary>
        /// 注册 service
        /// </summary>
        /// <param name="serviceCollection"></param>
        /// <param name="type"></param>
        private static void RegisterService(IServiceCollection serviceCollection, Type type)
        {
            Attribute attr = type.GetCustomAttribute(typeof(ServiceAttribute));
            if (attr == null)
            {
                return;
            }

            ServiceAttribute serviceAttr = (ServiceAttribute) attr;

            Type[] interfaces = type.GetInterfaces();
            if (interfaces.Length > 0)
            {
                // 有接口定义
                foreach (var iInterface in interfaces)
                {
                    switch (serviceAttr.Lifetime)
                    {
                        case ServiceLifetime.Singleton:
                            serviceCollection.AddSingleton(iInterface, type);
                            break;
                        case ServiceLifetime.Transient:
                            serviceCollection.AddTransient(iInterface, type);
                            break;
                        case ServiceLifetime.Scoped:
                            serviceCollection.AddScoped(iInterface, type);
                            break;
                    }
                }
            }
            else
            {
                // 无接口
                switch (serviceAttr.Lifetime)
                {
                    case ServiceLifetime.Singleton:
                        serviceCollection.AddSingleton(type);
                        break;
                    case ServiceLifetime.Transient:
                        serviceCollection.AddTransient(type);
                        break;
                    case ServiceLifetime.Scoped:
                        serviceCollection.AddScoped(type);
                        break;
                }
            }
        }
    }
}